import React, { PureComponent } from "react";
import { connect } from "dva";
// import { routerRedux, Link } from 'dva/router';
import {
  Form,
  Select,
  Input,
  Button,
  Row,
  Col,
  Cascader,
  Steps,
  message
} from "antd";
import bcx_utils from "../../common/bcx_utils";
import {
  getDistrictData, //省市区选择
  getDictInformation, //公共信息
  systemRoleIsCharge, //联系人手机验证接口
  systemPlatNewsSendVerificationCode, //获取验证码接口
  systemPlatNewsVerificationCode, //验证短信验证码接口
  systemComBaseInfoSave //注册接口
} from "../../services/api";
import IconS from "../../components/IconS";

import "./EnterpriseRegistration.less";

const FormItem = Form.Item;
const { Option } = Select;
const { Step } = Steps;

@connect(state => ({
  register: state.register
}))
@Form.create()
export default class EnterpriseRegistration extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      count: 0,
      areas: [], //省市区
      industryType: [], //行业类型
      institutionType: [], //机构类型
      economicType: [], //经济类型
      comType: [] //企业类型
    };
  }

  /******************************生命周期******************************/

  componentDidMount = () => {
    this.getAllType(); //获取所有类型
    this.getDistrict(); //省市区选择
  };
  componentWillUnmount = () => {
    //this.interval && clearInterval(this.interval);
    clearInterval(this.interval);
  };
  /******************************ajax请求******************************/
  //省市区
  getDistrict = () => {
    getDistrictData().then(data => {
      const areas = data.data.map(val => {
        return {
          value: val.regionId,
          label: val.regionName,
          children: val.childs.map(valChild => {
            return {
              value: valChild.regionId,
              label: valChild.regionName,
              children: valChild.childs.map(valChildChild => {
                return {
                  value: valChildChild.regionId,
                  label: valChildChild.regionName
                };
              })
            };
          })
        };
      });
      //console.log('areas:'+JSON.stringify(areas));
      this.setState({ areas });
    });
  };

  //获取验证码
  getMobileVerificationCode = () => {
    const mobile = this.props.form.getFieldValue("mobile");
    console.log("手机号码", mobile);
    if (!mobile || mobile === null) {
      message.error("联系手机不能为空！");
    }
    if (mobile && mobile !== null && mobile.length === 11) {
      systemRoleIsCharge({ mobile }).then(
        () => {
          let count = 59;
          this.setState({ count });
          this.interval = setInterval(() => {
            count -= 1;
            this.setState({ count });
            if (count === 0) {
              clearInterval(this.interval);
            }
          }, 1000);

          systemPlatNewsSendVerificationCode({ mobile }).then(
            res => {
              console.log("验证码是否发送成功:", res);
            },
            err => {
              console.log("获取验证码错误信息:", err);
            }
          );
        },
        err => {
          console.log("验证码处手机号码是否被注册:", err);
          // message.error("该手机已经注册成为个人用户,不能再注册");
          message.error(err);
        }
      );
    }
  };
  /******************************相关事件******************************/
  onGetCaptcha = () => {
    this.getMobileVerificationCode();
  };

  //获得行业类型,经济类型,机构类型,企业类型
  getAllType = () => {
    getDictInformation({
      codeTypes: ["industryType", "economicType", "institutionType", "comType"]
    }).then(res => {
      console.log("所有类型res:", res);
      //判断获取数据是否为空
      if (res.data) {
        const allTypeData = res.data;
        this.setState({
          industryType: allTypeData.industryType,
          economicType: allTypeData.economicType,
          institutionType: allTypeData.institutionType,
          comType: allTypeData.comType
        });
      }
    });
  };

  //行业类型选择
  renderIndustry = () => {
    return this.state.industryType.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ""}>
          {val.label}
        </Option>
      );
    });
  };

  //机构类型选择
  renderInstitution = () => {
    return this.state.institutionType.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ""}>
          {val.label}
        </Option>
      );
    });
  };

  //经济类型选择
  renderEconomic = () => {
    return this.state.economicType.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ""}>
          {val.label}
        </Option>
      );
    });
  };

  //企业类型选择
  renderCompany = () => {
    return this.state.comType.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ""}>
          {val.label}
        </Option>
      );
    });
  };

  handleSubmit = e => {
    e.preventDefault();

    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log("表单的值: ", values);
        const {
          comName,
          regAddress,
          economicType,
          industryType,
          comType,
          institutionType
        } = values;

        //验证手机号码是否被注册
        const mobile = this.props.form.getFieldValue("mobile");
        const code = this.props.form.getFieldValue("code");
        // const verificationCodeData = { mobile, code };

        if (mobile && mobile.length === 11) {
          systemPlatNewsVerificationCode({ mobile ,code })
            .then(res => {
              if (res.retType === "0") {
                console.log("手机号码未注册");

                const residence = this.props.form.getFieldValue("residence");
                const legalRepPhone = this.props.form.getFieldValue("mobile");
                let regprovince;
                let regcity;
                let area;
                if (residence) {
                  [regprovince, regcity, area] = [
                    residence[0],
                    residence[1],
                    residence[2]
                  ];
                }
                const comBaseInfoDto = {
                  comName,
                  regProvince: regprovince,
                  regCity: regcity,
                  regArea: area,
                  regAddress,
                  economicType,
                  industryType,
                  comType,
                  institutionType,
                  legalRepPhone
                };
                console.log("comBaseInfoDto", comBaseInfoDto);

                bcx_utils.preventRepeatAsync((callback) => callback((resolve) => {
                  systemComBaseInfoSave(comBaseInfoDto)
                    .then(submitRes => {
                      resolve(false);
                      console.log("注册接口", submitRes);
                      message.success("注册成功！");
                      this.props.history.push("EnterpriseRegistrationResult");
                    })
                    .catch(dd => {
                      resolve(false);
                      console.log(dd, "dd");
                    });
                }));
              }
            })
            .catch(errs => {
              // message.error(aa);
              console.log(errs);
            });
        }
      }
    });
  };

  /******************************render******************************/

  render() {
    const { count } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 4 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 20 },
        sm: { span: 20 }
      }
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0
        },
        sm: {
          span: 14,
          offset: 4
        }
      }
    };

    return (
      <div className="EnterpriseRegistration">
        <div className="enroll-header">
          <div className="head-portrait">
            <IconS type="logo-" />
            <span className="head-portrait-text">
              <span style={{ fontSize: "18px" }}>百保盾</span>
              <br />
              <span style={{ fontSize: "12px" }}>改变工作 改变你</span>
            </span>
          </div>
          <div className="head-portrait-register">
            <span
              style={{ cursor: "pointer" }}
              onClick={() => this.props.history.push("LogOn")}
            >
              登录{" "}
            </span>
          </div>
        </div>
        <div className="enroll-content">
          <div className="main">
            <h3>企业注册</h3>
            <div
              className="progress-bar"
              style={{ marginLeft: "45px", marginRight: "36px" }}
            >
              <Steps>
                <Step title="填写注册资料" />
                <Step title="开始体验" />
              </Steps>
            </div>
            <Form onSubmit={this.handleSubmit} style={{ marginTop: "40px" }}>
              <FormItem {...formItemLayout} label="行业类型">
                {getFieldDecorator("industryType", {
                  rules: [
                    {
                      required: true,
                      message: "请输入行业类型！"
                    }
                  ]
                })(
                  <Select placeholder="请选择">{this.renderIndustry()}</Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="经济类型">
                {getFieldDecorator("economicType", {
                  rules: [
                    {
                      required: true,
                      message: "请输入经济类型！"
                    }
                  ]
                })(
                  <Select placeholder="请选择">{this.renderEconomic()}</Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="机构类型">
                {getFieldDecorator("institutionType", {
                  rules: [
                    {
                      required: true,
                      message: "请输入机构类型！"
                    }
                  ]
                })(
                  <Select placeholder="请选择">
                    {this.renderInstitution()}
                  </Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="企业类型">
                {getFieldDecorator("comType", {
                  rules: [
                    {
                      required: true,
                      message: "请输入企业类型！"
                    }
                  ]
                })(
                  <Select placeholder="请选择">{this.renderCompany()}</Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="公司名称">
                {getFieldDecorator("comName", {
                  rules: [
                    {
                      pattern: /^[\u4e00-\u9fa5]{1,50}$/,
                      message: "请输汉字最大50位!"
                    },
                    {
                      required: true,
                      message: "请输入公司名称！"
                    }
                  ]
                })(<Input placeholder="校验通过内容" maxLength="50" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="注册地址">
                {getFieldDecorator("residence", {
                  // initialValue: ['浙江', '杭州', '西湖'],
                  rules: [
                    {
                      type: "array",
                      required: true,
                      message: "请选择你的注册地址!"
                    }
                  ]
                })(
                  <Cascader
                    showSearch
                    options={this.state.areas}
                    placeholder="请选择"
                  />
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="详细地址">
                {getFieldDecorator("regAddress", {
                  rules: [
                    {
                      required: true,
                      message: "请输入详细地址！"
                    }
                  ]
                })(
                  <div>
                    <Input placeholder="请输入" maxLength="100" />
                  </div>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="联系手机">
                <Row gutter={8}>
                  <Col span={24}>
                    {getFieldDecorator("mobile", {
                      rules: [
                        {
                          required: true,
                          message: "请输入联系手机！"
                        },
                        {
                          pattern: /^1[0-9]{10}$/,
                          message: "手机号格式错误！"
                        }
                      ]
                    })(
                      <div>
                        {/*<Input placeholder="请输入" maxLength='11' />*/}
                        <Input placeholder="请输入" maxLength="20" />
                      </div>
                    )}
                  </Col>
                </Row>
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="验证码"
              >
                <Row gutter={8}>
                  <Col span={18}>
                    {getFieldDecorator("code", {
                      rules: [
                        {
                          required: false,
                          message: "请输入验证码!"
                        },
                        {
                          // validator: (rule, value, cb) => {
                          //     if (value === undefined) {
                          //         cb('手机号码不能为空');
                          //     } else if (!(/^1[3456789]\d{9}$/.test(value))) {
                          //         cb('请输入正确手机号码!');
                          //     }
                          //     cb();
                          // }
                        }
                      ]
                    })(
                      <div>
                        <Input placeholder="请输入" maxLength="8" />
                      </div>
                    )}
                  </Col>
                  <Col span={6}>
                    <Button
                      type="primary"
                      disabled={count}
                      className="getCaptcha"
                      onClick={this.onGetCaptcha}
                    >
                      {count ? `${count} s` : "获取验证码"}
                    </Button>
                  </Col>
                </Row>
              </FormItem>
              <FormItem {...tailFormItemLayout}>
                <Button
                  onClick={() => this.props.history.push("Enroll")}
                  style={{ marginRight: "16px" }}
                >
                  取消
                </Button>
                <Button className="submit" type="primary" htmlType="submit">
                  确定
                </Button>
                {/* <Link className="login" to="/user/login">使用已有账户登录</Link> */}
              </FormItem>
            </Form>
          </div>
        </div>
      </div>
    );
  }
}
